package com.lie.prepare.multi_thread.even_checker;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by lie on 2018/4/9.
 */
public class EvenChecker implements Runnable {

    private IntGenerator intGenerator;
    private final int id;

    public EvenChecker(IntGenerator intGenerator, int id) {
        this.intGenerator = intGenerator;
        this.id = id;
    }

    public void run() {
        while (!intGenerator.isCancelled()) {
            int next = intGenerator.next();
//            System.out.println(Thread.currentThread().getName());
            if (next % 2 != 0) {
                System.out.println("! 错误，"+ next+ "并不是偶数");
                intGenerator.stop();
            }
        }
    }

    public static void test(IntGenerator g, int count){
        System.out.println("允许手动停止");
        ExecutorService threadPool = Executors.newCachedThreadPool();
        for (int i = 0; i < count; i++) {
            threadPool.execute(new EvenChecker(g, i));
        }
        threadPool.shutdown();
    }
}
